﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VehicleMaintenance.Framework;
using VehicleMaintenance.Comm;
using VehicleMaintenance.Models;
using VehicleMaintenance.BaseInfo;
using VehicleMaintenance.Events;

namespace VehicleMaintenance.Transaction
{
    public partial class PurchaseReturnsBillForm : AddOrEditBaseForm
    {

        #region 私有变量及属性

        /// <summary>
        /// 记录当前ID
        /// </summary>
        private int billID = 0;

        #endregion 私有变量及属性

        public PurchaseReturnsBillForm()
        {
            InitializeComponent();
			ucFormInput1.InitializeControls(typeof(Models.PurchaseReturnsBill));
            InitializeSepcial();
        }

        public PurchaseReturnsBillForm(int id)
        {
            InitializeComponent();
			ucFormInput1.InitializeControls(typeof(Models.PurchaseReturnsBill));
            InitializeSepcial();

            billID = id;
            state = State.Edit;
        }

        private void PurchaseReturnsBillForm_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.state == State.Edit)
                {
                    CarDBContext db = new CarDBContext();

                    PurchaseReturnsBill bill = db.PurchaseReturnsBill.Include("Goods").Include("CarType").Include("Staff").First(p => p.ID == this.billID);
                    ucFormInput1.SetValues(bill);

                    ucFormInput1.GetControlByName("GoodID").Text = bill.Good.Code;
                    ucFormInput1.GetControlByName("CarTypeID").Text = bill.CarType.Name;
                    ucFormInput1.GetControlByName("StaffID").Text = bill.Staff.Name;
                }
                else
                {
                    ucFormInput1.ClearData();

                    InitializeDefault();
                }
            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                CarDBContext db = new CarDBContext();

                if (!ucFormInput1.VerifyInput())
                {
                    return;
                }

                if (this.state == State.Edit)
                {
                    PurchaseReturnsBill bill = db.PurchaseReturnsBill.First(p => p.ID == billID);
                    int oldNumber = bill.Number;
                    ucFormInput1.GetValues(bill);
                    int newNumber = bill.Number;
                    db.Goods.Find(bill.GoodID).Number -= (newNumber - oldNumber);
                    db.SaveChanges();

                    this.ShowInfo("保存成功！");
                }
                else
                {
                    var bill = db.PurchaseReturnsBill.Create();

                    ucFormInput1.GetValues(bill);
                    //更新库存
                    db.Goods.Find(bill.GoodID).Number -= Convert.ToInt32(ucFormInput1.GetControlByName("Number").Text);
                    db.PurchaseReturnsBill.Add(bill);
                    db.SaveChanges();

                    if (MessageBox.Show(this, "保存成功，是否继续添加？", "提示", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        ucFormInput1.ClearData();
                        InitializeDefault();
                        ucFormInput1.GetControlByName("Code").Focus();
                    }
                    else
                    {
                        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    }
                }

            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            try
            {
                this.Close();
            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }

        private void InitializeSepcial()
        {
            try
            {
                ucFormInput1.GetControlByName("GoodID").Click += new EventHandler(good_Click);
                ucFormInput1.GetControlByName("CarTypeID").Click += new EventHandler(carType_Click);
                ucFormInput1.GetControlByName("StaffID").Click += new EventHandler(staff_Click);

				ucFormInput1.GetControlByName("Number").TextChanged += new EventHandler(num_TextChanged);
				ucFormInput1.GetControlByName("Number").KeyPress += new KeyPressEventHandler(KeyEvents.Number_KeyPress);
				ucFormInput1.GetControlByName("PurchasePrice").KeyPress += new KeyPressEventHandler(KeyEvents.Decimal_KeyPress);
				ucFormInput1.GetControlByName("ReturnValue").KeyPress += new KeyPressEventHandler(KeyEvents.Decimal_KeyPress);
				ucFormInput1.GetControlByName("ReturnPrice").KeyPress += new KeyPressEventHandler(KeyEvents.Decimal_KeyPress);
            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }

		void num_TextChanged(object sender, EventArgs e)
		{
			try
			{
				string str = ucFormInput1.GetControlByName("Number").Text.Trim();
				int number;
				if (Int32.TryParse(str, out number))
				{
					if (ucFormInput1.GetControlByName("ReturnValue").Text.Trim().Length > 0)
					{
						ucFormInput1.GetControlByName("ReturnPrice").Text = (number * Convert.ToDecimal(ucFormInput1.GetControlByName("ReturnValue").Text)).ToString();
					}					
				}
				else
				{
					ucFormInput1.GetControlByName("ReturnPrice").Text = "0.0";
				}
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}

        void good_Click(object sender, EventArgs e)
        {
            try
            {               
                TextBox txt = (sender as TextBox);

                GoodListForm form = new GoodListForm();
                if (form.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    txt.Text = form.Good.Code;
                    txt.Tag = form.Good.GoodID;

                    ucFormInput1.GetControlByName("GoodName").Text = form.Good.Name;
                    ucFormInput1.GetControlByName("PurchasePrice").Text = form.Good.PurchasePrice.ToString();
                    ucFormInput1.GetControlByName("ReturnValue").Text = form.Good.RetailPrice.ToString();
                    ucFormInput1.GetControlByName("ReturnPrice").Text = form.Good.RetailPrice.ToString();
					ucFormInput1.GetControlByName("Units").Text = form.Good.Units;

					CarDBContext db = new CarDBContext();
					CarType carType = db.CarType.Find(form.Good.CarTypeID);
					ucFormInput1.GetControlByName("CarTypeID").Text = carType.Name;
					ucFormInput1.GetControlByName("CarTypeID").Tag = carType.CarTypeID;
                }
            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }

        void carType_Click(object sender, EventArgs e)
        {
            try
            {
                
                TextBox txt = (sender as TextBox);

                CarTypeForm form = new CarTypeForm();
                if (form.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    txt.Text = form.CarType.Name;
                    txt.Tag = form.CarType.CarTypeID;
                }

            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }
        void staff_Click(object sender, EventArgs e)
        {
            try
            {
                TextBox txt = (sender as TextBox);

                StaffListForm form = new StaffListForm();
                if (form.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    txt.Text = form.Staff.Name;
                    txt.Tag = form.Staff.StaffID;
                }

            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }

        void InitializeDefault()
        {
            CarDBContext db = new CarDBContext();
            string str = DateTime.Now.ToString("yyyyMMdd");
            PurchaseReturnsBill bill = db.PurchaseReturnsBill.OrderByDescending(p => p.ID).FirstOrDefault(p => p.Code.StartsWith(str));
            if (bill == null)
            {
                str += "001";
            }
            else
            {
                str = (Convert.ToInt64(bill.Code) + 1).ToString();
            }
            ucFormInput1.GetControlByName("Code").Text = str;
        }
    }
}